package fr.efrei.tradesys.hibernate.beans;

import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.opensymphony.xwork2.ActionContext;

import fr.efrei.tradesys.treatments.Converter;
import fr.efrei.tradesys.treatments.Formatter;

@Entity
@Table(name = "OWNED")
@SequenceGenerator(name = "S_OWNED", sequenceName = "S_OWNED")
public class Owned
{

	private int				idOwned;
	private AppUser		appUser;
	private Currency	currency;
	private double		units;
	private Double		equivalent;

	public Owned()
	{
	}

	public Owned(AppUser appUser, Currency currency, double units)
	{
		this.appUser = appUser;
		this.currency = currency;
		this.units = units;
	}

	@Id
	@Column(name = "IDOWNED", unique = true, nullable = false, precision = 6, scale = 0)
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "S_OWNED")
	public int getIdOwned()
	{
		return idOwned;
	}

	public void setIdOwned(int idOwned)
	{
		this.idOwned = idOwned;
	}

	@ManyToOne
	@JoinColumn(name = "LOGIN", nullable = false)
	public AppUser getAppUser()
	{
		return appUser;
	}

	public void setAppUser(AppUser appUser)
	{
		this.appUser = appUser;
	}

	@ManyToOne
	@JoinColumn(name = "CODE", nullable = false)
	public Currency getCurrency()
	{
		return currency;
	}

	public void setCurrency(Currency currency)
	{
		this.currency = currency;
	}

	@Column(name = "UNITS", precision = 10, scale = 2, columnDefinition = "numeric", nullable = false)
	public double getUnits()
	{
		return units;
	}

	public void setUnits(double units)
	{
		this.units = units;
	}

	@Transient
	public String getUnitsFormatted()
	{
		return new Formatter().format(getUnits(), 2);
	}

	@Transient
	public double getEquivalent()
	{
		if (equivalent == null)
		{
			Map<String, Object> session = ActionContext.getContext().getSession();
			AppUser u = (AppUser) session.get("user");
			equivalent = new Converter().convertCurrenciesSell(this.units,
					this.currency, u.getFavoriteCurrency());
		}
		return equivalent;
	}

	@Transient
	public String getEquivalentFormatted()
	{
		return new Formatter().format(getEquivalent(), 2);
	}

}
